package com.seven.monior;

import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;

import com.seven.monior.AppInfo.Global;
import com.seven.monior.TaskInfo.TaskInfo;

public class RefreshReceiver extends BroadcastReceiver {
	private DatabaseHelper databaseHelper;
	private SQLiteDatabase db;
	private PackageManager pm = Global.pm;
	private ActivityManager am = Global.am;
	private ConnectivityManager cm = Global.cm;

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub

		databaseHelper = new DatabaseHelper(context);

		if (intent.getAction().equals(Global.ACTION_RESET)) {

			resetData();
			// db.delete("apps", null, null);

		} else if (intent.getAction().equals(Global.ACTION_UPDATE_TASKLIST)) {

			if (!MonitorService.SyncingDB) {
				MonitorService.SyncingDB = true;
				final Context c = context;
				new Thread(new Runnable() {

					@Override
					public void run() {

						// long t3 = System.currentTimeMillis();
						// Log.e("Service", "SyncingDB_CV \t" + t3);
						// syncDB_CV(c);
						// long t4 = System.currentTimeMillis();
						// Log.e("Service", "SyncedDB_CV \t" + t4);
						// Log.e("Service", "SyncedDB_CV Time\t" + (t4 - t3));

						long t1 = System.currentTimeMillis();
						Log.e("Service", "SyncingDB \t" + t1);
						syncDB();
						long t2 = System.currentTimeMillis();
						Log.e("Service", "SyncedDB \t" + t2);
						Log.e("Service", "SyncedDB Time\t" + (t2 - t1));

						MonitorService.SyncingDB = false;
					}
				}).start();
			}

		} else if (intent.getAction().equals(Global.ACTION_INSERT)) {
			// Context c = context;
			//
			// long t1 = System.currentTimeMillis();
			// Log.e("Service", "INSERT \t" + t1);
			// insertTest();
			// long t2 = System.currentTimeMillis();
			// Log.e("Service", "INSERT \t" + t2);
			// Log.e("Service", "INSERT Time\t" + (t2 - t1));
			//
			// long t3 = System.currentTimeMillis();
			// Log.e("Service", "INSERT CP \t" + t3);
			// insertTestCP(c);
			// long t4 = System.currentTimeMillis();
			// Log.e("Service", "INSERT CP \t" + t4);
			// Log.e("Service", "INSERT CP Time\t" + (t4 - t3));

		}

		// Cursor cs = db.query("apps", null, null, null, null, null, null);
		// int nCount = cs.getCount();
		// cs.close();
		// if (nCount <= 0) {
		// initDB();
		// Log.w("INIT DB", "INIT DB");
		// } else {
		//
		// Log.w("UPDATE DB", "UPDATE DB");
		// }

		databaseHelper.close();
		//
		// Intent it = new Intent(Global.ACTION_UPDATE_UI);
		// context.sendBroadcast(it);

	}

	// private void insertTest() {
	// db = databaseHelper.getWritableDatabase();
	// ContentValues cv = new ContentValues();
	// cv.put("uid", 55555);
	// for (int i = 0; i < 100; i++)
	// db.insert("apps", null, cv);
	// db.close();
	// }
	//
	// private void insertTestCP(Context context) {
	// ContentResolver cr = context.getContentResolver();
	// Uri uri = Uri.parse("content://com.seven.monitor/apps");
	// ContentValues cv = new ContentValues();
	// cv.put("uid", 55555);
	// for (int i = 0; i < 100; i++)
	// cr.insert(uri, cv);
	// }

	private void syncDB() {
		db = databaseHelper.getWritableDatabase();
		ArrayList<TaskInfo> taskInfos = Global.taskInfoList;
		// db.delete("apps", null, null);

		for (int i = 0; i < taskInfos.size(); i++) {
			TaskInfo tInfo = taskInfos.get(i);
			int nUID = tInfo.getUID();

			Cursor cs = db.query("apps", null, "uid=" + nUID, null, null, null,
					null);
			if (cs.moveToFirst()) {

				if (cs.getInt(cs.getColumnIndex("uid")) == nUID) {
					ContentValues cv = new ContentValues();
					cv.put("mobile_received", tInfo.m_lMobile_Rx);
					cv.put("mobile_last_received", tInfo.m_lMobile_last_Rx);
					cv.put("mobile_sent", tInfo.m_lMobile_Tx);
					cv.put("mobile_last_sent", tInfo.m_lMobile_last_Tx);
					cv.put("total_received", tInfo.m_lTotal_Rx);
					cv.put("total_last_received", tInfo.m_lTotal_last_Rx);
					cv.put("total_sent", tInfo.m_lTotal_Tx);
					cv.put("total_last_sent", tInfo.m_lTotal_last_Tx);
					cv.put("cputime", tInfo.getTotalCpuTime());
					String where = "uid=" + nUID;
					db.update("apps", cv, where, null);
					// Log.d("SYNC DB", "UPDATE " + nUID);
				}
			} else {
				ContentValues cv = new ContentValues();
				cv.put("uid", nUID);
				cv.put("date", System.currentTimeMillis());
				cv.put("is_running", 1);
				cv.put("mobile_received", tInfo.m_lMobile_Rx);
				cv.put("mobile_last_received", tInfo.m_lMobile_last_Rx);
				cv.put("mobile_sent", tInfo.m_lMobile_Tx);
				cv.put("mobile_last_sent", tInfo.m_lMobile_last_Tx);
				cv.put("total_received", tInfo.m_lTotal_Rx);
				cv.put("total_last_received", tInfo.m_lTotal_last_Rx);
				cv.put("total_sent", tInfo.m_lTotal_Tx);
				cv.put("total_last_sent", tInfo.m_lTotal_last_Tx);
				cv.put("cputime", tInfo.getTotalCpuTime());

				db.insert("apps", null, cv);
				// Log.d("SYNC DB", "INSERT " + nUID);
			}
			cs.close();
		}
		db.close();
	}

	private void syncDB_CV(Context context) {
		ContentResolver cr = context.getContentResolver();
		Uri uri = Uri.parse("content://com.seven.monitor/apps");

		ArrayList<TaskInfo> taskInfos = Global.taskInfoList;

		for (int i = 0; i < taskInfos.size(); i++) {
			TaskInfo tInfo = taskInfos.get(i);
			int nUID = tInfo.getUID();

			Cursor cs = cr.query(uri, null, "uid=" + nUID, null, null);

			if (cs.moveToFirst()) {

				if (cs.getInt(cs.getColumnIndex("uid")) == nUID) {
					ContentValues cv = new ContentValues();
					cv.put("mobile_received", tInfo.m_lMobile_Rx);
					cv.put("mobile_last_received", tInfo.m_lMobile_last_Rx);
					cv.put("mobile_sent", tInfo.m_lMobile_Tx);
					cv.put("mobile_last_sent", tInfo.m_lMobile_last_Tx);
					cv.put("total_received", tInfo.m_lTotal_Rx);
					cv.put("total_last_received", tInfo.m_lTotal_last_Rx);
					cv.put("total_sent", tInfo.m_lTotal_Tx);
					cv.put("total_last_sent", tInfo.m_lTotal_last_Tx);
					cv.put("cputime", tInfo.getTotalCpuTime());
					String where = "uid=" + nUID;

					cr.update(uri, cv, where, null);
					// Log.d("SYNC DB", "UPDATE " + nUID);
				}
			} else {
				ContentValues cv = new ContentValues();
				cv.put("uid", nUID);
				cv.put("date", System.currentTimeMillis());
				cv.put("is_running", 1);
				cv.put("mobile_received", tInfo.m_lMobile_Rx);
				cv.put("mobile_last_received", tInfo.m_lMobile_last_Rx);
				cv.put("mobile_sent", tInfo.m_lMobile_Tx);
				cv.put("mobile_last_sent", tInfo.m_lMobile_last_Tx);
				cv.put("total_received", tInfo.m_lTotal_Rx);
				cv.put("total_last_received", tInfo.m_lTotal_last_Rx);
				cv.put("total_sent", tInfo.m_lTotal_Tx);
				cv.put("total_last_sent", tInfo.m_lTotal_last_Tx);
				cv.put("cputime", tInfo.getTotalCpuTime());
				cr.insert(uri, cv);

				// Log.d("SYNC DB", "INSERT " + nUID);
			}
			cs.close();
		}

	}

	private void resetData() {
		db = databaseHelper.getWritableDatabase();
		db.delete("apps", null, null);
		ArrayList<Integer> uids = new ArrayList<Integer>();
		List<PackageInfo> pInfos = pm
				.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
		for (int i = 0; i < pInfos.size(); i++) {
			boolean found = false;
			for (int j = 0; j < uids.size(); j++) {
				if (uids.get(j) == pInfos.get(i).applicationInfo.uid) {
					found = true;
					break;
				}
			}
			if (!found) {
				uids.add(pInfos.get(i).applicationInfo.uid);
			}
		}
		for (int i = 0; i < uids.size(); i++) {
			ContentValues cv = new ContentValues();
			cv.put("uid", uids.get(i));
			cv.put("mobile_received", 0);
			cv.put("mobile_last_received", 0);
			cv.put("mobile_sent", 0);
			cv.put("mobile_last_sent", 0);
			cv.put("total_received", 0);
			cv.put("total_last_received", 0);
			cv.put("total_sent", 0);
			cv.put("total_last_sent", 0);
			cv.put("cputime", 0);
			db.insert("apps", null, cv);
			// Log.i("RESET", "INSERT" + uids.get(i));
		}
		db.close();
		MonitorService.Reseting = false;
		// db.update("apps", cv, null, null);
		Log.e("RESET", "RESET");
	}

}
